import { createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
import axios from "axios";

interface Address {
  address: string;
  nickname: string;
  tel: string;
  id: string;
}

export const fetchAddressList = createAsyncThunk(
  "address/fetchAddressList",
  async () => {
    const resp = await axios.get("/api/address");
    return resp.data;
  }
);

export const addAddressList = createAsyncThunk(
  "address/addAddressList",
  async (
    data: {
      address: string;
      nickname: string;
      tel: string;
    },
    thunkAPI
  ) => {
    const resp = await axios.post("/api/address/add", data);
    // 分发actions
    thunkAPI.dispatch(fetchAddressList());
  }
);

export const editAddressList = createAsyncThunk(
  "address/addAddressList",
  async (
    data: Address,
    thunkAPI
  ) => {
    const resp = await axios.post("/api/address/edit", data);
    // 分发actions
    thunkAPI.dispatch(fetchAddressList());
  }
);


interface AddressState {
  address: Address | null;
  addressList: Address[];
}

const initialState: AddressState = {
  address: null,
  addressList: [],
};

const addressSlice = createSlice({
  name: "address",
  initialState,
  reducers: {},
  extraReducers: {
    [fetchAddressList.fulfilled.type](
      state,
      action: PayloadAction<AddressState>
    ) {
      state.address = action.payload.address;
      state.addressList = action.payload.addressList;
    },
  },
});

export default addressSlice;
